package com.lemon.stock.compose

import android.content.Context
import android.content.Intent
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.lemon.stock.R
import com.lemon.stock.entity.Stock
import com.lemon.stock.theme.*
import com.lemon.stock.ui.StockActivity
import com.lemon.stock.viewmodel.StocksViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

private var listStockIds: MutableList<String> = arrayListOf()

/**
 * 首页
 * 关注的股票列表
 *
 */
@Preview
@Composable
fun HomeScreen(){
    val context = LocalContext.current
    val mViewModel: StocksViewModel = viewModel()
    val stocks = mViewModel.stocks.observeAsState(arrayListOf())

    val coroutineScope = rememberCoroutineScope()
    val refreshingState = remember{ mutableStateOf(REFRESH_STOP) }

    mViewModel.fetchStocks()

    val launcher: ActivityResultLauncher<Intent> =
        rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) {
                activityResult ->
            val intent: Intent? = activityResult.data
            if(intent!=null){
                val reload = intent.extras?.get("reload")?.toString()
                if(reload=="yes"){
                    mViewModel.fetchStocks()
                }
            }
        }
    Scaffold(
        topBar ={
            TopAppBar(
                title = {Text(text = stringResource(id = R.string.nav_home))},
                elevation = 8.dp,
                actions = {
                    IconButton(onClick = {
                        /**
                         * 增加自选股票
                         */
                        stockClick(launcher, context, -1)
                    }) {
                        Icon(
                            painter = painterResource(id = R.drawable.ic_btn_add),
                            contentDescription = null
                        )
                    }
                }
            ) 
        },
        content = {
            SwipeToRefreshLayout(
                refreshingState = refreshingState.value,
                onRefresh = {
                    refreshingState.value = REFRESH_START
                    coroutineScope.launch{
                        mViewModel.remoteStocks(listStockIds)
                        delay(1000)
                        refreshingState.value = REFRESH_STOP
                    }
                },
                progressIndicator = {
                    Surface(elevation = 10.dp, shape = CircleShape) {
                        CircularProgressIndicator(
                            modifier = Modifier
                                .size(36.dp)
                                .padding(4.dp)
                        )
                    }
                    //ProgressIndicator()
                }
            ){
                /**
                 * 股票列表
                 */
                HomeScreenContent(launcher = launcher, context = context, stocks = stocks)
            }
        }
    )
}

/**
 * 股票列表
 */
//@Preview
@Composable
fun HomeScreenContent(launcher: ActivityResultLauncher<Intent>, context: Context, stocks: State<List<Stock>>){
    listStockIds = mutableListOf<String>()
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(8.dp)

    ) {
        StockCaption()
        ListItemDivider()
        LazyColumn(
            modifier = Modifier.padding(bottom = 60.dp)
        ) {
            itemsIndexed(stocks.value){ index, stock->
                listStockIds.add(stock.stockExchange+stock.stockId)
                StockItem(launcher = launcher, context = context, stock = stock, index=index)
                ListItemDivider()
            }
        }
    }
}

/**
 * 股票列表--表头
 *
 */
@Composable
fun StockCaption(){
    Row(
        verticalAlignment = Alignment.CenterVertically,
        modifier = Modifier
            .fillMaxWidth()
            .height(38.dp)
    ){
        Text(stringResource(id = R.string.stock_name)+"/"+stringResource(id = R.string.stock_hold), style = styleHead, modifier = Modifier.weight(1f))
        Text(stringResource(id = R.string.stock_price)+"/"+stringResource(id = R.string.stock_cost), style = styleHead, modifier = Modifier.weight(1f))
        Text(stringResource(id = R.string.stock_worth)+"/"+stringResource(id = R.string.text_advise), style = styleHead, modifier = Modifier.weight(1f))
        Text(stringResource(id = R.string.stock_gain)+"/"+stringResource(id = R.string.stock_gain_ratio), style = styleHead, modifier = Modifier.weight(1f))
    }
}

/**
 * 股票列表--内容
 * @param launcher  启动Activity的发射器， 打开股票详情活动页面
 * @param context  启动Activity的发射器， 打开股票详情活动页面
 * @param stock 股票实体类
 * @param index 股票实体类在列表中的序号（索引号）
 * @param modifier 修饰语
 *
 */
@Composable
fun StockItem(launcher: ActivityResultLauncher<Intent>, context: Context, stock: Stock, index: Int, modifier: Modifier = Modifier){
    Column(
        //onClick = {},
        verticalArrangement = Arrangement.Center,
        modifier = modifier
            .fillMaxWidth()
            .height(68.dp)
            .clickable(onClick = {
                stockClick(launcher = launcher, context = context, index)
            })
    ){
        //val adviseId =
        var advise = stringResource(id = when{
            (stock.buyLine>0 && stock.buyLine>stock.stockPrice) -> R.string.advise_buy
            (stock.sellLine>0 && stock.sellLine<stock.stockPrice) -> R.string.advise_sell
            (stock.sellLine>0 && stock.sellLine<stock.stockPrice*1.02) -> R.string.advise_sell
            (stock.buyLine>0 && stock.buyLine>stock.stockPrice*0.98) -> R.string.advise_buy
            else-> R.string.advise_wait
        })
        /*
        var advise = stringResource(id = R.string.advise_wait)
        if(stock.buyLine>0 && stock.buyLine>stock.stockPrice){
            advise = stringResource(id = R.string.advise_wait)
        }
        if(stock.holdStock>0){

        }*/

        Row(){
            Text(text = stock.stockName, style = styleBold, modifier = Modifier.weight(1f))
            Text(text = stock.stockPrice.toString()+"元", style = (if(stock.stockPrice<stock.costPrice) styleLose else styleEarn), modifier = Modifier.weight(1f))
            Text(text = String.format("%.2f", stock.worthMoney), style = styleBodyRight, modifier = Modifier.weight(1f))
            Text(text = String.format("%.2f", stock.profitMoney), style = (if(stock.profitMoney<=0) styleLose else styleEarn), modifier = Modifier.weight(1f))
        }
        Row(){
            Text(text = stock.holdStock.toString(), style = styleLower, modifier = Modifier.weight(1f))
            Text(text = String.format("%.2f", stock.costPrice), style = styleLowerRight, modifier = Modifier.weight(1f))
            Text(text = advise, style = styleLowerRight, modifier = Modifier.weight(1f))
            Text(text = String.format("%.2f", stock.profitRatio)+"%", style = styleLowerRight, modifier = Modifier.weight(1f))
        }
    }
}

/**
 * 股票列表中项目的单击事件
 * @param launcher  启动Activity的发射器， 打开股票详情活动页面
 * @param context  启动Activity的发射器， 打开股票详情活动页面
 * @param index 股票实体类在列表中的序号（索引号）
 *
 */
private fun stockClick(launcher: ActivityResultLauncher<Intent>, context: Context, index: Int){
    val listockid = listStockIds.toTypedArray()
    val intent = StockActivity.newIntent(context, listockid, index)
    launcher.launch(intent)
}

